package com.teamide.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

	/** 纯日期格式：yyyyMMddHHmmss */
	public final static String PURE_DATETIME_PATTERN = "yyyyMMddHHmmss";

	/** 标准日期格式：yyyy-MM-dd hh:mm:ss */
	public final static String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd hh:mm:ss";

	public static Date now() {
		return new Date();
	}

	public static Long nowPure() {
		return Long.valueOf(nowFormat(PURE_DATETIME_PATTERN));
	}

	public static String nowFormat() {
		return nowFormat(DEFAULT_DATETIME_PATTERN);
	}

	public static String nowFormat(String format) {
		return format(now(), format);
	}

	public static String format(Date date, String format) {
		SimpleDateFormat simpleDateFormat = getFormat(format);
		return simpleDateFormat.format(date);
	}

	public static SimpleDateFormat getFormat() {
		return getFormat(DEFAULT_DATETIME_PATTERN);
	}

	public static SimpleDateFormat getFormat(String format) {
		if (StringUtil.isEmpty(format)) {
			format = DEFAULT_DATETIME_PATTERN;
		}
		return new SimpleDateFormat(format);
	}

	public static Date toDate(String formatDate) throws ParseException {
		if (StringUtil.isEmpty(formatDate)) {
			return null;
		}
		formatDate = formatDate.replaceAll("[^\\d]", "");
		String format = "yyyyMMddHHmmsss";
		int length = formatDate.length();
		if (length >= 4 && length < 6) {
			format = "yyyy";
		} else if (length >= 6 && length < 8) {
			format = "yyyyMM";
		} else if (length >= 8 && length < 10) {
			format = "yyyyMMdd";
		} else if (length >= 10 && length < 12) {
			format = "yyyyMMddHH";
		} else if (length >= 12 && length < 14) {
			format = "yyyyMMddHHmm";
		} else if (length >= 14 && length < 15) {
			format = "yyyyMMddHHmmss";
		} else if (length >= 15) {
			format = "yyyyMMddHHmmsss";
		}
		return toDate(formatDate, format);
	}

	public static Date toDate(String formatDate, String format) throws ParseException {
		SimpleDateFormat simpleDateFormat = getFormat(format);
		return simpleDateFormat.parse(formatDate);
	}
}
